<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="30%"
    :before-close="handleClose"
  >
    <div>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="上级部门" prop="parentid">
          <el-tree-select
            default-expand-all
            node-key="id"
            filterable
            v-model="ruleForm.parentid"
            :data="treeData"
            check-strictly
            :render-after-expand="false"
            :props="{
              label: 'name',
            }"
            style="width: 100%"
            placeholder="选择上级部门"
          >
          </el-tree-select>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input
            placeholder="输入部门名称"
            style="width: 100%"
            v-model="ruleForm.name"
          />
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input
            placeholder="排序"
            style="width: 100%"
            v-model="ruleForm.order"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { addApi } from "@/plugins/api/system/dept";
const props = defineProps({
  treeData: {
    type: Array,
    default: [],
  },
});
let ruleForm = ref({});
let rules = {
  parentid: [
    {
      required: true,
      message: "请选择上级部门",
      trigger: "change",
    },
  ],
  name: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
  order: [{ required: true, message: "请填写排序", trigger: "blur" }],
};
let dialogVisible = ref(false);
function handleClose(done) {
  // dialogVisible.value = false;
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
}
let title = ref("");
let ruleFormRef = ref(null);
function initFun(type, row) {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  if (type == "add") {
    title.value = "新增部门";
    ruleForm.value = {};
  } else {
    title.value = "编辑部门";
    ruleForm.value = Object.assign({}, row);
    ruleForm.value.order = row.order_number;
  }

  dialogVisible.value = true;
}
const emit = defineEmits(["refreshList"]);
function submit() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      addApi(ruleForm.value).then((data) => {
        if (ruleForm.value.id) {
          ElMessage.success("编辑成功！");
        } else {
          ElMessage.success("新增成功！");
        }
        dialogVisible.value = false;
        emit("refreshList");
      });
    }
  });
}
defineExpose({
  initFun,
});
</script>
<style scoped lang="scss"></style>
